import {
  Body,
  Controller,
  Delete,
  Get,
  Param,
  ParseIntPipe,
  Post,
  Req,
} from '@nestjs/common';
import type { Request } from 'express';
import { UserService } from './user.service';
import { CreateUserDto } from './create-user-dto';
import { Public } from '../../common/decorators/public.decorator';
import type { JwtPayload } from '../../types/auth.d.ts';
import { UnauthorizedException } from '@nestjs/common';
@Controller('user')
export class UserController {
  constructor(private readonly userService: UserService) {}

  @Get('info')
  async getUserInfo(@Req() request: Request) {
    // 从 request['user'] 中获取验证后的payload，添加类型断言
    const payload = request['user'] as JwtPayload;

    if (!payload) {
      throw new UnauthorizedException('用户未登录或token无效');
    }

    try {
      const result = await this.userService.getUserInfo(payload);

      return result;
    } catch (error) {
      console.error('错误详情:', {
        errorName: error.name,
        errorMessage: error.message,
        errorStack: error.stack,
      });
      throw error;
    }
  }

  @Get(':id')
  getUser(@Param('id', ParseIntPipe) id: number) {
    console.log(typeof id); // 默认是字符串类型的 ParseIntPipe 会将其转换为数字类型 这是一个小小的改进
    return this.userService.findOne(id);
  }

  @Get()
  getAllUsers() {
    return this.userService.findAll();
  }

  @Public()
  @Post()
  createUser(@Body() body: CreateUserDto) {
    return this.userService.create(body);
  }
  @Delete(':id')
  deleteUser(@Param('id', ParseIntPipe) id: number) {
    return this.userService.delete(id);
  }
}
